package Search;

import Data.MassageData;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.*;

public class SearchFile {
    private MassageData massageData;
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";

    public MassageData getMassageData() {
        return massageData;
    }

    public void setMassageData(MassageData massageData) {
        this.massageData = massageData;
    }

    public SearchFile(MassageData massageData) {
        this.massageData = massageData;
    }

    public MassageData search() throws ClassNotFoundException, SQLException, IOException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);
        String sql="select *from file where id=?";
        PreparedStatement operation=Conn.prepareStatement(sql);
        operation.setString(1,massageData.getFile_id());

        ResultSet resultSet=operation.executeQuery();
        byte[] t = null;
        if(resultSet.next())
        {
            System.out.println("找到对应的文件了");
            //如果有这个文件
            String path=resultSet.getString("file_path");
            File file=new File(path);
            massageData.setMD5(resultSet.getString("MD5"));
            massageData.setSuffix_name(resultSet.getString("suffix_name"));

            resultSet.close();
            operation.close();
            Conn.close();

            System.out.println(massageData.getFile_id()+" "+massageData.getFile_name());
            //读取文件并且返回

            if (file != null)
            {
                byte[] buffer = new byte[1024*5];
                t = new byte[(int) file.length()];
                InputStream is = Files.newInputStream(file.toPath());
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int len;
                while ((len = is.read(buffer)) != -1)
                {
                    bos.write(buffer, 0, len);
                }
                t = bos.toByteArray();
            }
            massageData.setBytes(t);
        }
        return massageData;
    }
}
